package com.googlecode.xapper

import static org.junit.Assert.*
import static org.hamcrest.Matchers.*
import com.sun.org.apache.xalan.internal.xsltc.compiler.ForEach
import org.junit.*

import nu.xom.*

import groovy.xml.MarkupBuilder

import com.googlecode.xapper.HtmlQuery

public class TestHtmlQuery{

	@Test
	public void shouldFindTheCorrectNumberOfChildren() {
		def writer = new StringWriter()
		
		def markup = new MarkupBuilder(writer)
		
		markup.html(xmlns: 'http://www.w3.org/1999/xhtml') {
			body {
				div {
					p('Paragraph A')
					p('Paragraph B')
				}
			}
		}
		
		//println(writer.toString())
		
		def builder = new Builder()
		
		def reader = new StringReader(writer.toString())
		
		def document = builder.build(reader)
		
		def query = HtmlQuery.query(document.getRootElement())
		
		List<Elements> elements = query.findElementsMatching('//html:div/html:p')
		
		assertThat(elements.size(), is(2))
		
		for(e in elements) {
			assertThat(e.getLocalName(), is(equalTo("p")))
		}
	}
	
	@Test
	public void shouldFindElementsByAttribute() {
		def writer = new StringWriter()
		
		def markup = new MarkupBuilder(writer)
		
		markup.html(xmlns: 'http://www.w3.org/1999/xhtml') {
			body {
				div(class: 'lemon')
				div(class: 'pear')
				div(class: 'pear') {
					
				}
			}
		}
		
		def xhtml = writer.toString()
		
		def builder = new Builder()
		
		def document = builder.build(new StringReader(xhtml))
		
		def query = HtmlQuery.query(document)
		
		def elements = query.findElementsMatching("//html:*[@class='pear']")
		
		assertThat(elements.size(), is(2))
	
		elements = query.findElementsMatching("//html:*[@class='lemon']")
		
		assertThat(elements.size(), is(1))
	}
}
